package org.springblade.common.config;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.modules.auth.utils.NoticeAlertUtil;
import org.springblade.modules.monitor.entity.WorkOrder;
import org.springblade.modules.desk.mapper.AlertsMapper;
import org.springblade.modules.monitor.mapper.WorkOrderMapper;
import org.springblade.modules.desk.vo.AlertsVO;
import org.springblade.modules.system.entity.Param;
import org.springblade.modules.system.mapper.ParamMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import static org.springblade.modules.auth.utils.NoticeAlertUtil.transferMessage;

/**
 * @ClassName ScheduleTask
 * @Description
 * @Author zhang_xfei
 * @DATE 2020 2020/5/18 14:24
 **/
@Component // 此注解必加
@EnableScheduling // 此注解必加
public class ScheduleTask {
	@Autowired
	private AlertsMapper alertsMapper;

	@Autowired
	private NoticeAlertUtil noticeAlertUtil;

	@Autowired
	private WorkOrderMapper workOrderMapper;


	@Autowired
	private ParamMapper paramMapper;

	@Value("${spring.notice.noticeflag}")
	private Boolean noticeflag;

	private static final Logger LOGGER =  LoggerFactory.getLogger(ScheduleTask.class);
	public synchronized String  alert(){
		if(!noticeflag){
			return null;
		}
		//轮询数据库中状态为0的数据
		List<AlertsVO> list = alertsMapper.selectAlertsAndSeverity();
		if(!CollectionUtils.isEmpty(list)){
			//参数列表
			List<Param> paramList = paramMapper.selectAll();
			Map<String, String> params = transferListToMap(paramList);
			//从数据库中获取最大工单号
			WorkOrder maxWorkOrder = workOrderMapper.selectMaxWorkOrderRecord();
			String serial = "";
			LocalDate localDate = LocalDate.now();
			String yyyyMMdd = localDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
			if (maxWorkOrder == null) {
				serial = String.format("%06d", 0);
			}else {
				String workOrderIdStr= maxWorkOrder.getWorkOrderId().toString();
				//如果不存在当天的工单，从0开始计数
				if(workOrderIdStr.startsWith(yyyyMMdd)){
					int length = workOrderIdStr.length();
					String substring = workOrderIdStr.substring(length - 6, length);
					serial = String.format("%06d", Integer.valueOf(substring) + 1);
				}else {
					serial = String.format("%06d", 0);
				}
			}

			//向工单表中插入数据
			AtomicLong serialNum = new AtomicLong(Long.valueOf(yyyyMMdd + serial));
			for (AlertsVO tempAlert : list) {
				//通过tempAlert 查询事件等级
				WorkOrder workOrder = new WorkOrder();
				workOrder.setWorkOrderId(serialNum.get());
				workOrder.setTitle(tempAlert.getSubject());
				workOrder.setOrderDescribe(tempAlert.getMessage());
				workOrder.setCurrentOrderState(1);
				workOrder.setCurrentUserId(1123598821738675201L);
				workOrder.setAlertId(tempAlert.getAlertid());
				workOrder.setOrderType(tempAlert.getSeverity());
				workOrder.setCreateTime(LocalDateTime.now());
				workOrder.setUpdateTime(LocalDateTime.now());
				workOrder.setOrderType(tempAlert.getSeverity());
				//转换hostId,用于计算健康度
				JSONObject message =  transferMessage(tempAlert.getMessage());
				workOrder.setHostName(message.getString("hostName"));
				workOrderMapper.insert(workOrder);
				alertsMapper.updateNoticeStateById(tempAlert.getAlertid(),1);
				long num = serialNum.get();

				//判断是否进行相应通知
				if("1".equalsIgnoreCase(params.get("weixinNoticeFlag"))){
					noticeAlertUtil.weixinAlert(tempAlert,num,params);
				}

				if("1".equalsIgnoreCase(params.get("dingdingNoticeFlag"))){
					noticeAlertUtil.dingdingAlert(tempAlert,num,params);
				}

				if("1".equalsIgnoreCase(params.get("emailNoticeFlag"))){
					noticeAlertUtil.emailAlert(tempAlert,num,params);
				}

				if("1".equalsIgnoreCase(params.get("messageNoticeFlag"))){
					noticeAlertUtil.messageAlert(tempAlert,num,params);
				}

				//故障修正进行短信、语音通知
				if(tempAlert.getPEventid()==null){

					if("1".equalsIgnoreCase(params.get("messageNoticeFlag"))){
						noticeAlertUtil.messageAlert(tempAlert,num,params);
					}

					if("1".equalsIgnoreCase(params.get("phoneCallNoticeFlag"))){
						noticeAlertUtil.phoneCallAlert(tempAlert,num,params);
					}
				}



				//更新状态
				serialNum.addAndGet(1);
			}
		}
		return "SUCCESS";
	}

	private Map<String,String> transferListToMap(List<Param> params){
		Map<String, String> map = new HashMap<>();
		for (Param param : params) {
			map.put(param.getParamKey(), param.getParamValue());
		}
		return map;
	}


}
